package org.i1510.common.controller;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.i1510.common.bean.PageBean;
import org.i1510.common.dao.ISysQuartzDao;
import org.i1510.common.po.SysQuartz;
import org.i1510.common.service.ISysQuartzService;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.SpringContextUtil;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;






/**
 * @author Administrator
 * 只支持 实现Job接口的任务
 */
@Controller
@RequestMapping(value = "/admin/sysQuartz")
public class SysQuartzController {
	private static final Logger logger = LoggerFactory.getLogger(SysQuartzController.class);
	@Autowired
	private ISysQuartzService iSysQuartzService;
	@Autowired
	private ISysQuartzDao iSysQuartzDao;
	
	private ResultMapper mapper;
	
	/**
	*@Author Rambo
	*@Desc：执行job（只执行一次）
	*@param sysQuartz
	*@param errors
	*@return
	*@throws SchedulerException TODO
	*@Version  SysQuartzController.java,v 1.1 2014-11-13 下午5:06:22 
	*/
	@RequestMapping(value = "/exeJob", method = RequestMethod.GET)
	@ResponseBody
	public String exeJob(@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) throws SchedulerException {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
	        scheduler.triggerJob(sysQuartz.getFdTaskName(),  sysQuartz.getFdGroup());
	        mapper = ResultMapper.generateSuccess();
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：修改任务的触发时间
	*@param sysQuartz
	*@param errors
	*@return
	*@throws SchedulerException
	*@throws ParseException TODO
	*@Version  SysQuartzController.java,v 1.1 2014-11-12 上午10:10:22 
	*/
	@RequestMapping(value = "/updateJob", method = RequestMethod.GET)
	@ResponseBody
	public String updateJob(@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) throws SchedulerException, ParseException {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{

			Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(sysQuartz.getFdTriggerName(),  sysQuartz.getFdGroup()); 
			trigger.setCronExpression(sysQuartz.getFdCronExpression());  //"*/10 * * * * ? *"            
            Date date = scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);  
            if(null != date){
            	mapper = ResultMapper.generateSuccess();
            	mapper.appendResult("nextFireTime", DateUtils.convertDateToString(date, DateUtils.PATTERN_DATETIME));
            }else{
            	mapper = ResultMapper.generateFailure();
            }
	        
		}
		
		return mapper.toJson();
	}	
	
	/**
	*@Author Rambo
	*@Desc：唤起任务
	*@param sysQuartz
	*@param errors
	*@return
	*@throws SchedulerException TODO
	*@Version  SysQuartzController.java,v 1.1 2014-11-12 上午10:09:58 
	*/
	@RequestMapping(value = "/resumeJob", method = RequestMethod.GET)
	@ResponseBody
	public String resumeJob(@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) throws SchedulerException {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
	        scheduler.resumeJob(sysQuartz.getFdTaskName(),  sysQuartz.getFdGroup());
	        mapper = ResultMapper.generateSuccess();
		}
		
		return mapper.toJson();
	}	
	/**
	*@Author Rambo
	*@Desc：删除任务
	*@param sysQuartz
	*@param errors
	*@return
	*@throws SchedulerException TODO
	*@Version  SysQuartzController.java,v 1.1 2014-11-12 上午10:09:50 
	*/
	@RequestMapping(value = "/deleteJob", method = RequestMethod.GET)
	@ResponseBody
	public String deleteJob(@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) throws SchedulerException {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
	        if(scheduler.deleteJob(sysQuartz.getFdTaskName(),  sysQuartz.getFdGroup())){
	        	mapper = ResultMapper.generateSuccess();	        	
	        }else{
	        	mapper = ResultMapper.generateFailure();
	        }
	        
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：启动定时任务(第一次启动)
	*@param sysQuartz
	*@param errors
	*@return
	*@throws SchedulerException
	*@throws ClassNotFoundException
	*@throws ParseException TODO
	*@Version  SysQuartzController.java,v 1.1 2014-11-11 下午9:48:29 
	*/
	@RequestMapping(value = "/start", method = RequestMethod.GET)
	@ResponseBody
	public String start(@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) throws SchedulerException, ClassNotFoundException, ParseException {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();  	  
	        JobDetail jobDetail = new JobDetail(sysQuartz.getFdTaskName(),  sysQuartz.getFdGroup(), Class.forName(sysQuartz.getClassName()));  	  
	        Trigger  trigger = new CronTrigger(sysQuartz.getFdTriggerName(), sysQuartz.getFdGroup(),sysQuartz.getFdCronExpression());
	          
	        scheduler.scheduleJob(jobDetail, trigger);  
	        scheduler.start();  
	        mapper = ResultMapper.generateSuccess();
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：暂停任务
	*@param sysQuartzBean
	*@param errors
	*@return
	*@throws SchedulerException TODO
	*@Version  SysQuartzController.java,v 1.1 2014-11-11 下午9:56:05 
	*/
	@RequestMapping(value = "/pauseJob", method = RequestMethod.GET)
	@ResponseBody
	public String pauseJob(@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) throws SchedulerException {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
	        scheduler.pauseJob(sysQuartz.getFdTaskName(),  sysQuartz.getFdGroup());
	        mapper = ResultMapper.generateSuccess();
		}
		
		return mapper.toJson();
	}
	@RequestMapping(value = "/pauseXmlJob", method = RequestMethod.GET)
	@ResponseBody
	public String pauseXmlJob(@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) throws SchedulerException, ParseException {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
			StdScheduler schedulerFactory = (StdScheduler)SpringContextUtil.getBean("schedulerFactory");		
//			QuartzHandler quartzHandler = new QuartzHandler(schedulerFactory);
//			quartzHandler.updateCronExpression("doTime", Scheduler.DEFAULT_GROUP, "*/15 * * * * ? *");
//			quartzHandler.getTrigger("doTime", Scheduler.DEFAULT_GROUP);

			schedulerFactory.pauseJob("messageJob",  Scheduler.DEFAULT_GROUP);



	        mapper = ResultMapper.generateSuccess();
		}
		
		return mapper.toJson();
	}
	
	/**
	*@Author Rambo
	*@Desc：保存对象
	*@param sysQuartz
	*@param errors
	*@return TODO
	*@Version  SysQuartzController.java,v 1.1 2013-11-15 下午4:20:56 
	*/
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request,@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iSysQuartzService.save(sysQuartz,request);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：删除对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysQuartzController.java,v 1.1 2014-9-2 下午3:38:17 
	*/
	@RequestMapping(value = "/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iSysQuartzService.delete(docId);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：查看对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysQuartzController.java,v 1.1 2014-9-2 下午3:39:35 
	*/
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			SysQuartz sysQuartz = iSysQuartzService.findById(docId);
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", sysQuartz);
		}		
		return mapperRtn.toJson();
	}
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("sysQuartz") SysQuartz sysQuartz,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			List  sysQuartzs = iSysQuartzService.getPage(sysQuartz, pageBean,conditions);
			int totalCount =  iSysQuartzService.getPageCount(sysQuartz,conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData",sysQuartzs);
			
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}		
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：状态修改
	*@param request
	*@param docId
	*@param docStatus
	*@param errors
	*@return TODO
	*@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
	*/
	@RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(docId)){
				SysQuartz sysQuartz = new SysQuartz();
				
				sysQuartz.setDocId(docId);
				sysQuartz.setDocStatus(docStatus);
				mapper = iSysQuartzService.save(sysQuartz,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}
			
		}
		
		return mapper.toJson();
	}
}